package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public Long submit(Orders orders) {
        //1.获取当前用户的id
        long userId = BaseContext.getCurrentId();
        //2.查询当前用户的购物车数据
        //2.1 构造查询构造器
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //2.2 添加查询条件
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        //2.3 执行查询操作
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(cartLambdaQueryWrapper);
        //2.4 判断获取的购物车数据是否为空
        if (shoppingCarts==null||shoppingCarts.size()==0){
            //若购物车是空的则不能下单，抛出自定义异常
            throw new CustomException("购物车为空，不能下单");
        }
        //3. 查询用户数据(订单需要用户的地址和手机号等数据)
        User user = userService.getById(userId);
        //4. 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook==null){//判断获取的地址是否为空
            //若为空，则抛出异常
            throw new CustomException("地址信息有误，不能下单");
        }
        //生成订单号
        long orderId = IdWorker.getId();
        AtomicInteger amount = new AtomicInteger();//累加金额，计算总金额
        //5. 遍历购物车数据：计算总金额，批量保存到订单明细
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((item)->{
            OrderDetail orderDetail = new OrderDetail();//实例化订单明细对象
            orderDetail.setOrderId(orderId);//关联订单
            orderDetail.setNumber(item.getNumber());//当前菜品或套餐的数量
            orderDetail.setDishFlavor(item.getDishFlavor());//菜品口味
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());//菜品或套餐名称
            orderDetail.setImage(item.getImage());//菜品或套餐图片
            orderDetail.setAmount(item.getAmount());//菜品或套餐单价
            // 计算公式: 菜品的金额 乘以(multiply) 份数
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());//单价乘以份数，累加成总金额
            return orderDetail;
        }).collect(Collectors.toList());

        //6. 设置订单主键id(与订单号相同)
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());//设置下单时间
        orders.setCheckoutTime(LocalDateTime.now());//设置支付时间
        orders.setStatus(2);//订单当前状态  1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(new BigDecimal(amount.get()));//设置订单总金额
        orders.setUserId(userId);//设置用户id
        orders.setNumber(String.valueOf(orderId));//设置订单号
        orders.setUserName(user.getName());//设置用户名
        orders.setConsignee(addressBook.getConsignee());//设置收货人
        orders.setPhone(addressBook.getPhone());//设置手机号
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //7. 向订单表插入一条数据
        this.save(orders);
        //8. 向订单明细表中插入数据
        orderDetailService.saveBatch(orderDetailList);
        //9. 下单成功后清空购物车
        shoppingCartService.remove(cartLambdaQueryWrapper);
        return orderId;
    }


    /*=======================================*/

    /**
     * 查询订单信息
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Object findAll(Integer page, Integer pageSize, Long number, String beginTime, String endTime) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        //根据订单号,进行模糊查询--一定要对订单号进行判断是否为空
        wrapper.like(!ObjectUtils.isEmpty(number),Orders::getNumber,number);

        if (!ObjectUtils.isEmpty(beginTime)&&!ObjectUtils.isEmpty(endTime)) {
            wrapper.between(Orders::getOrderTime,beginTime,endTime);
        }
        //添加排序条件
        wrapper.orderByDesc(Orders::getCheckoutTime);


        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //执行查询
        page(ordersPage,wrapper);

        //获取当前页数据
        List<Orders> records = ordersPage.getRecords();

        List<Orders> collectList = records.stream().map(item -> {
            //添加收货人姓名
            item.setUserName(item.getConsignee());
            return item;
        }).collect(Collectors.toList());
        //回传必须存在，将分页后的结果回传
        ordersPage.setRecords(collectList);
        return ordersPage;
    }
}
